var ns, app, WXPhotoPicker;
app = new Vue({
    el: '#app',
    data: {
        tabList: [
            { ID: 1, Name: '扫码放行' },
            { ID: 2, Name: '出门登记' },
            { ID: 3, Name: '出门记录' },
        ],
        activeTab: 0,
        //扫码放行
        formone: {
            pageindex: 0,
            pagesize: 100,
            keywords: '',
        },
        OneList: [],
        //出门登记
        formtwo: {
            ProjectID: 0,
            ProjectName: '',
            VisitorName: '',
            VisitCount:0,
            PhoneNumber: '',
            VisitedName: '',
            VisitedPhone: '',
            IDCardNumber: '',
            ItemName: '',
            CarNumber: '',
            VisitTypeID: 0,
            VisitTypeName: '',
            ReleaseExplain: '',//放行说明
            ApplyCompany: '',//申请单位
        },
        IsVisitTypeOpen:false,
        typelist2: [],
        imglist: [],
        maxuploadcount: CONFIG.maxuploadcount,
        IsProjectOpen:false,
        ProjectList: [],
        //出门记录
        searchProjectList: [],
        showsearchparam:false,
        IsShowSearchThird:false,
        formthird: {
            pageindex: 0,
            pagesize: 100,
            keywords: '',
            startTime: '',
            endTime: '',
            activeDate: 0,
            ProjectIDs: [],
            VisitTypeIDs: [],
        },
        thirdList: [],
    },
    methods: {
        onClickTab(index, title) {
            this.doCloseSearchThird();
            if (this.activeTab == 0) {
                this.get_data_one();
            }
            if (this.activeTab == 1) {

            }
            if (this.activeTab == 2) {
                this.get_data_third();
            }
        },
        get_data() {
            this.get_project_list();
            this.get_data_two();
            this.getSearchParams();

            this.get_data_one();
        },
        //扫码放行
        handleEnterOne(event) {
            // 检查按下的键是否是Enter
            if (event.keyCode == 13) {
                this.get_data_one();
            }
        },
        doSearchClearOne() {
            this.formone.keywords = '';
            this.get_data_one();
        },
        get_data_one: function () {
            var that = this;
            var options = {};
            options.pagesize = that.formone.pagesize;
            options.pageindex = that.formone.pageindex;
            options.Type = 1;//类型 1-扫码出行 2-出门记录
            var ProjectIDs=[];
            var VisitTypeIDs=[];
            options.ProjectIDs = JSON.stringify(ProjectIDs);
            options.VisitTypeIDs = JSON.stringify(VisitTypeIDs);
            options.keyWords =  that.formone.keywords;
            options.StartTime = "";
            options.EndTime = "";
            options.action = "getreleasestriplist";
            ns.post(options, function(succeed, data, err) {
                if (succeed) {
                    that.OneList = data.list;
                } else if (err) {
                    api.toast({
                        msg: err,
                        duration: 2000,
                        location: 'bottom'
                    });
                }
            }, {
                toast: true
            });
        },
        open_details_fx(item){
            ns.openWin('outdoor_detail','放行条详情',{
                ID:item.ID,
                ShowType:1,
            });
        },
        do_leave: function(item) {
            var that = this;
            api.confirm({
                title: '提示',
                msg: '确认要放行吗？?',
                buttons: ['放行', '取消']
            }, function (ret, err) {
                if (ret.buttonIndex == 1) {
                    ns.post({
                        action: 'savaconfirmpassage',
                        ID: item.ID,
                    }, function (succeed, data, err) {
                        if (succeed) {
                            api.toast({
                                msg: '操作成功',
                                duration: 2000,
                                location: 'bottom'
                            });
                            that.get_data_one();
                        } else if (err) {
                            api.toast({
                                msg: err,
                                duration: 2000,
                                location: 'bottom'
                            });
                        }
                    });
                }
            });
            // api.confirm({
            //     title: '提示',
            //     msg: '确认要放行吗？',
            //     buttons: ['放行', '取消']
            // }, function(ret, err) {
            //     if (ret.buttonIndex == 1) {
            //         var options = {};
            //         options.action = "dosavevisitleave";
            //         options.ID = item.ID;
            //         ns.post(options, function(succeed, data, err) {
            //             if (succeed) {
            //                 api.toast({
            //                     msg: '操作成功',
            //                     duration: 2000,
            //                     location: 'bottom'
            //                 });
            //                that.get_data();
            //             } else if (err) {
            //                 api.toast({
            //                     msg: err,
            //                     duration: 2000,
            //                     location: 'bottom'
            //                 });
            //             }
            //         });
            //     }
            // });
        },
        do_open_scan_login: function (item) {
            var that = this;
            ns.confirmPer('camera', function () {
                setTimeout(function () {
                    that.do_open_scan_login_start();
                }, 200)
            })
        },
        do_open_scan_login_start: function () {
            var that = this;
            ns.openFrame('scanner_frm', {
                type: 0
            });
        },
        //出门登记 
        //选择项目
        get_project_list: function () {
            var that = this;
            var options = {
                action: 'getmytopprojectlist'
            };
            ns.post(options, function (succeed, data, err) {
                if (succeed) {
                    that.ProjectList = data.list;
                    that.doSelectProject(that.ProjectList[0])
                }
            });
        },
        do_chooseProject: function () {
            var that = this;
            that.IsProjectOpen = true;
        },
        doCloseProject: function () {
            var that = this;
            that.IsProjectOpen = false;
        },
        doSelectProject: function (item) {
            var that = this;
            that.IsProjectOpen = false;
            that.formtwo.ProjectID = item.ID;
            that.formtwo.ProjectName = item.Name;
            // that.get_relation_name();
        },
        do_select_project: function () {
            var that = this;
            ns.openWin('chooseproject_frm', '选择项目', {
                selecttype: 1,
            });
        },
        //选择通行事由
        get_data_two: function () {
            var that = this;
            var options = {};
            options.action = "getvisittypelist";
            ns.post(options, function (succeed, data, err) {
                if (succeed) {
                    that.typelist2 = data.list2;
                    if (that.typelist2.length > 0) {
                        that.doSelectVisitType(that.typelist2[0]);
                    }
                } else if (err) {
                    api.toast({
                        msg: err,
                        duration: 2000,
                        location: 'bottom'
                    });
                }
            });
        },
        do_chooseVisitType: function () {
            var that = this;
            that.IsVisitTypeOpen = true;
        },
        doCloseVisitType: function () {
            var that = this;
            that.IsVisitTypeOpen = false;
        },
        doSelectVisitType: function (item) {
            var that = this;
            that.IsVisitTypeOpen = false;
            that.formtwo.VisitTypeID = item.ID;
            that.formtwo.VisitTypeName = item.Name;
            
        },
        checknumber: function (str) {
            var re = /^[0-9a-zA-Z]*$/g; //判断字符串是否为数字和字母组合
            if (!re.test(str)) {
                return false;
            } else {
                return true;
            }
        },
        get_relation_name: function () {
            var that = this;
            var options = {};
            options.action = 'getroomrelationdata';
            options.ProjectID = that.formtwo.ProjectID
            ns.post(options, function (succeed, data, err) {
                if (succeed) {
                    that.formtwo.VisitorName = data.RealName;
                    that.formtwo.PhoneNumber = data.PhoneNumber;
                }
            });
        },
        choose_picture: function () {
            var that = this;
            ns.confirmPer('camera', function () {
                that.choose_picture_start();
            })
        },
        choose_picture_start: function () {
            var that = this;
            if (that.imglist.length >= that.maxuploadcount) {
                api.toast({
                    msg: '最多支持' + that.maxuploadcount + '张图片',
                    duration: 2000,
                    location: 'bottom'
                });
                return;
            }
            api.actionSheet({
                cancelTitle: '取消',
                buttons: ['拍照', '从相册选择']
            }, function (ret, err) {
                //拍照
                if (ret.buttonIndex == 1) {
                    that.upload_choose_picture();
                    return;
                }
                //从相册选择
                if (ret.buttonIndex == 2) {
                    that.choose_picture_album();
                    return;
                }
                //取消 
                else {
                    return false;
                }
            });
        },
        upload_choose_picture: function () {
            var that = this;
            api.getPicture({
                sourceType: 'camera',
                encodingType: 'jpg',
                destinationType: 'url',
                allowEdit: false,
                saveToPhotoAlbum: true,
            }, function (ret, err) {
                if (ret && ret.data) {
                    that.do_imageFilter(ret.data);
                    // that.imglist.push({
                    //     ID: 0,
                    //     url: ret.data,
                    //     thumbPath: ret.data,
                    //     isupload: true
                    // });
                }
            });
        },
        choose_picture_album: function () {
            var that = this;
            WXPhotoPicker.open({
                max: that.maxuploadcount - that.imglist.length,
                type: 'image',
            }, function (ret) {
                if (ret) {
                    if (ret.list.length > 0) {
                        ret.list.forEach((item) => {
                            that.do_imageFilter(item.path);
                            // that.imglist.push({
                            //     ID: 0,
                            //     url: item.path,
                            //     thumbPath: item.path,
                            //     isupload: true
                            // });
                        });
                    }
                }
            });
        },
         //图片压缩
         do_imageFilter:function(path){
            var that=this;
            var imgName = Date.now() + '.jpg';
            var target_w = 500;
            var imageFilter = api.require('imageFilter');
            imageFilter.getAttr({
                path: path
            }, function(ret, err) {
                if (ret.status) {
                    if (ret.width < target_w) {
                        target_w = ret.width;
                    }
                    var original_w = ret.width;
                    var original_h = ret.height;
                    var scale = original_w / target_w;
                    var target_h = Math.round(original_h / scale);
                    imageFilter.compress({
                        img: path,
                        quality: 1,
                        size: {
                            w: target_w,
                            h: target_h
                        },
                        save: {
                            album: false,
                            imgPath: api.cacheDir + '/upload/',
                            imgName: imgName
                        }
                    }, function(ret, err) {
                        if (ret.status) {
                            var imgFullName=api.cacheDir + '/upload/' + imgName;
                            that.imglist.push({
                                ID: 0,
                                url: imgFullName,
                                thumbPath: imgFullName,
                                isupload: true
                            });
                        }else{
                            alert( JSON.stringify( err ) );
                        }
                    });
                }
            });
        },
        remove_img: function (index, item) {
            var that = this;
            that.imglist.splice(index, 1);
        },
        do_viewimages: function (activeIndex) {
            var that = this;
            var imageUrls = [];
            for (var i = 0; i < that.imglist.length; i++) {
                imageUrls.push(that.imglist[i].url);
            }
            var imageBrowser = api.require('imageBrowser');
            imageBrowser.openImages({
                showList: false,
                activeIndex: activeIndex,
                imageUrls: imageUrls
            });
        },
        do_save: function () {
            var that = this;
            var options = {};
            var filelist = [];
            for (var i = 0; i < that.imglist.length; i++) {
                filelist.push(that.imglist[i].url);
            }
            if (that.formtwo.ProjectID <= 0) {
                api.toast({
                    msg: '请选择项目',
                    duration: 2000,
                    location: 'bottom'
                });
                return;
            }
            if (!that.formtwo.ApplyCompany) {
                api.toast({
                    msg: '请填写申请单位',
                    duration: 2000,
                    location: 'bottom'
                });
                return;
            }
            
            if (!that.formtwo.VisitorName) {
                api.toast({
                    msg: '请填写申请人',
                    duration: 2000,
                    location: 'bottom'
                });
                return;
            } 
            if (that.formtwo.VisitTypeID == 0 || that.formtwo.VisitTypeID == undefined) {
                api.toast({
                    msg: '请选择通行事由',
                    duration: 2000,
                    location: 'bottom'
                });
                return;
            }
            if (that.formtwo.PhoneNumber != '' && !that.checknumber(that.formtwo.PhoneNumber)) {
                api.toast({
                    msg: '联系方式输入不正确',
                    duration: 2000,
                    location: 'bottom'
                });
                return;
            }
            options = ns.extend(that.formtwo, {
                action: 'dosavevisit',
                type: 2
            });
            ns.post(options, function (succeed, data, err) {
                if (succeed) {
                    api.toast({
                        msg: '操作成功',
                        duration: 2000,
                        location: 'bottom'
                    });
                    // // 保存成功后是否跳转到门岗出入列表
                    // setTimeout(function () {
                    //     api.closeWin();
                    // }, 500)

                    //重置表单
                    that.formtwo.ProjectID=0;
                    that.formtwo.ProjectName='';
                    that.formtwo.ApplyCompany='';
                    that.formtwo.VisitorName='';
                    that.formtwo.PhoneNumber='';
                    that.formtwo.CarNumber='';
                    that.formtwo.VisitTypeID=0;
                    that.formtwo.VisitTypeName='';
                    that.formtwo.ReleaseExplain=''; 
                    that.doSelectProject(that.ProjectList[0]);
                    that.doSelectVisitType(that.typelist2[0]);
                    //跳转到记录页面
                    that.activeTab = 2;
                    that.onClickTab();

                } else if (err) {
                    api.toast({
                        msg: err,
                        duration: 2000,
                        location: 'bottom'
                    });
                }
            }, {
                toast: true,
                files: {
                    file: filelist
                }
            });
        },
        //出门记录
        handleEnterThird(event) {
            // 检查按下的键是否是Enter
            if (event.keyCode == 13) {
                this.doSearch();
            }
        },
        doSearchClearThird() {
            this.formthird.keywords = '';
            this.doSearch();
        },
        open_details: function(item) {
            ns.openWin('gate_sentry_details_frm', '门岗通行记录', {
                id: item.ID
            });
        },
        get_data_third: function () {
            var that = this;
            var options = {};
            options.pagesize = that.formthird.pagesize;
            options.pageindex = that.formthird.pageindex;
            options.Type = 2;//类型 1-扫码出行 2-出门记录
            var ProjectIDs=that.formthird.ProjectIDs;
            if(ProjectIDs.indexOf(0)>-1){
                ProjectIDs=[];
            }
            options.ProjectIDs =JSON.stringify(ProjectIDs);
            var VisitTypeIDs=that.formthird.VisitTypeIDs;
            if(VisitTypeIDs.indexOf(0)>-1){
                VisitTypeIDs=[];
            }
            options.VisitTypeIDs = JSON.stringify(VisitTypeIDs);
            options.keyWords = that.formthird.keywords;
            options.StartTime = that.formthird.startTime;
            options.EndTime = that.formthird.endTime;
            options.action = "getreleasestriplist";
            ns.post(options, function(succeed, data, err) {
                if (succeed) {
                    that.thirdList = data.list;
                } else if (err) {
                    api.toast({
                        msg: err,
                        duration: 2000,
                        location: 'bottom'
                    });
                }
            }, {
                toast: true
            });
        },
        getSearchParams: function () {
            var that = this;
            var options = {};
            options.action = "getanalysissearchparam";
            ns.post(options, function (succeed, data, err) {
                if (succeed) {
                    that.searchProjectList = data.projectList;
                    // if(that.searchProjectList!=undefined&&that.searchProjectList.length>0){
                    //     that.doSearchProject(that.searchProjectList[0].ID,that.searchProjectList[0].Name); 
                    // }
                } else if (err) {
                    api.toast({
                        msg: err,
                        duration: 2000,
                        location: 'bottom'
                    });
                }
            });
        },
        doSearchThird(){
            var that = this;
            that.showsearchparam = !that.showsearchparam;
            this.IsShowSearchThird=!this.IsShowSearchThird;
            if(this.IsShowSearchThird){
                setTimeout(function () {
                    that.initPicker();
                }, 100);
            }
        },
        doCloseSearchThird(){
            this.showsearchparam=false;
            this.IsShowSearchThird=false;
        },
        doReset: function () {
            var that = this;
            that.formthird.startTime = '';
            that.formthird.endTime = '';
            that.formthird.activeDate = 0;
            that.formthird.ProjectIDs = [];
            that.formthird.VisitTypeIDs = [];
        },
        doSearch: function () {
            var that = this;
            that.doCloseSearchThird();
            that.get_data_third();
        },
        doSearchProject: function (ID,Name) {
            var that = this;
            that.formthird.ProjectIDs=[];
            that.formthird.ProjectIDs.push(ID);
        },
        doSearchVisitType: function (ID,Name) {
            var that = this;
            that.formthird.VisitTypeIDs=[];
            that.formthird.VisitTypeIDs.push(ID);
        },
        doClickDay: function (dataValue) {
            var that = this;
            that.formthird.activeDate = dataValue;
            var startDate = '',
                endDate = '';
            if (dataValue == 1) {
                var currentDate = dateRangeUtil.getCurrentDate();
                startDate= moment(new Date()).subtract(3, 'days').format("YYYY-MM-DD");
                endDate =  dateRangeUtil.getDateString(currentDate);
            }
            if (dataValue == 2) {
                var currentDate = dateRangeUtil.getCurrentDate();
                startDate= moment(new Date()).subtract(7, 'days').format("YYYY-MM-DD");
                endDate= dateRangeUtil.getDateString(currentDate);
            }
            if (dataValue == 3) {
                var currentDate = dateRangeUtil.getCurrentDate();
                startDate= moment(new Date()).subtract(30, 'days').format("YYYY-MM-DD");
                endDate= dateRangeUtil.getDateString(currentDate);
            }
            that.formthird.startTime = startDate;
            that.formthird.endTime = endDate;
        },
        initPicker: function () {
            var _this = this;
            (function ($, doc) {
                $.init();
                $.ready(function () {
                    //开始日期
                    var btn = document.querySelector('#startdate');
                    btn.addEventListener('tap', function () {
                        var _self = this;
                        if (_self.picker) {
                            if(_this.formthird.startTime){
                                _self.picker.setSelectedValue(_this.formthird.startTime);//回显
                            }
                            _self.picker.show(function (rs) {
                                _this.formthird.startTime = rs.value;
                                _self.picker.dispose();
                                _self.picker = null;
                            });
                        } else {
                            var optionsJson = this.getAttribute('data-options') || '{}';
                            var options = JSON.parse(optionsJson);
                            var id = this.getAttribute('id');
                            _self.picker = new $.DtPicker(options);
                            if(_this.formthird.startTime){
                                _self.picker.setSelectedValue(_this.formthird.startTime);//回显
                            }
                            _self.picker.show(function (rs) {
                                var timer = setTimeout(function () {
                                    clearTimeout(timer);
                                    _this.formthird.startTime = rs.value;
                                }, 300);
                                _self.picker.dispose();
                                _self.picker = null;
                            });
                        }
                    }, false);
                    //结束日期
                    var btnEnd = document.querySelector('#enddate');
                    btnEnd.addEventListener('tap', function () {
                        var _self = this;
                        if (_self.picker) {
                            if(_this.formthird.endTime){
                                _self.picker.setSelectedValue(_this.formthird.endTime);//回显
                            }
                            _self.picker.show(function (rs) {
                                _this.formthird.endTime = rs.value;
                                _self.picker.dispose();
                                _self.picker = null;
                            });
                        } else {
                            var optionsJson = this.getAttribute('data-options') || '{}';
                            var options = JSON.parse(optionsJson);
                            var id = this.getAttribute('id');
                            _self.picker = new $.DtPicker(options);
                            if(_this.formthird.endTime){
                                _self.picker.setSelectedValue(_this.formthird.endTime);//回显
                            }
                            _self.picker.show(function (rs) {
                                var timer = setTimeout(function () {
                                    clearTimeout(timer);
                                    _this.formthird.endTime = rs.value;
                                }, 300);
                                _self.picker.dispose();
                                _self.picker = null;
                            });
                        }
                    }, false);
                });
            })(mui, document);
        },
    }
});
apiready = function () {
    api.parseTapmode();
    ns = window.Foresight.Util;
    WXPhotoPicker = api.require('WXPhotoPicker');

    setTimeout(function () {
        app.get_data();
    }, 500)

    api.addEventListener({
        name: 'do_load_data'
    }, function (ret, err) {
        app.onClickTab();
    });
};
